<?php
/**
 * 门店自提发货单处理Lib类
 * 
 * @author: wangbiao@shopex.cn
 */
class wap_delivery
{
    function __construct($app)
    {
        $this->app = $app;
    }

    /**
     * 通过外部发货单号找到关联的订单号
     *
     * @param $outer_delivery_bn    ome发货单号
     * @return Array
     */
    public function getList($filter, $offset=0, $limit=2, $orderby='')
    {
        $wapDeliveryObj    = app::get('wap')->model('delivery');
        
        $fields            = 'delivery_id, delivery_bn, status, print_status, process_status, shop_id, outer_delivery_bn, ship_name, ship_area, ship_addr, ship_mobile, ship_tel, branch_id, confirm, is_cod, order_bn, total_amount,logi_name';
        $dataList          = $wapDeliveryObj->getList($fields, $filter, $offset, $limit, $orderby);
        foreach ($dataList as $key => $val)
        {
            if($val['outer_delivery_bn'])
            {
//                 $dataList[$key]['order_info']    = $this->getDeliverBnByOrderInfo($val['outer_delivery_bn']);
                //在wap_delivery表中新加 order_bn,total_amount字段  是在生成新的o2o发货单是直接从订单表中带过来的  @wangjianjun
                $dataList[$key]["order_info"] = array(
                    "order_bn" => $val["order_bn"],
                    "total_amount" => $val["total_amount"],
                    "is_cod_type" => $this->formatDeliveryStatus('is_cod', $val['is_cod'])
                );
                
                //$dataList[$key]['order_number']  = 1;
                
                #发货单明细
                $dataList[$key]['delivery_items']    = $this->getDeliveryItemList($val['outer_delivery_bn']);
            }
            $dataList[$key]['dly_status']    = $this->formatDeliveryStatus('status', $val['status']);
            $dataList[$key]['dly_confirm']   = $this->formatDeliveryStatus('confirm', $val['confirm']);
            
            #门店自提仓库对应店铺信息
            $dataList[$key]['shop_info']     = $this->getBranchShopInfo($val['branch_id']);
        }
        
        return $dataList;
    }
    
    /**
     * 通过外部发货单号找到关联的订单号
     * 
     * @param $outer_delivery_bn    ome发货单号
     * @return Array
     */
    public function getDeliverBnByOrderId($outer_delivery_bn)
    {
        $deliveryObj    = app::get('ome')->model('delivery');
        
        $sql            = "SELECT dord.order_id FROM sdb_ome_delivery_order AS dord 
                           LEFT JOIN sdb_ome_delivery AS d ON(dord.delivery_id=d.delivery_id)
                           WHERE d.delivery_bn='". $outer_delivery_bn ."' AND (d.parent_id=0 OR d.is_bind='true') AND d.disabled='false' 
                           AND d.status NOT IN('failed','cancel','back','return_back')";
        $order_ids      = $deliveryObj->db->selectrow($sql);
        
        return $order_ids['order_id'];
    }
    
    /**
     * 通过外部发货单号找到ome发货单号详细信息
     *
     * @param $outer_delivery_bn    ome发货单号
     * @return $delivery_bn
     */
    public function getOmeDeliveryInfo($outer_delivery_bn)
    {
        $deliveryObj    = app::get('ome')->model('delivery');
        
        $sql            = "SELECT delivery_id, delivery_bn FROM sdb_ome_delivery WHERE delivery_bn='". $outer_delivery_bn ."' 
                           AND (parent_id=0 OR is_bind='true') AND disabled='false' AND status NOT IN('failed','cancel','back','return_back')";
        $delivery_info  = $deliveryObj->db->selectrow($sql);
        
        return $delivery_info;
    }
    
    /**
     * 通过外部发货单号找到订单详细信息
     *
     * @param $outer_delivery_bn    ome发货单号
     * @return $orderInfo
     */
    public function getDeliverBnByOrderInfo($outer_delivery_bn)
    {
        $ordersObj         = app::get('ome')->model('orders');
        
        $order_id    = $this->getDeliverBnByOrderId($outer_delivery_bn);
        if(empty($order_id))
        {
            return '';
        }
        
        $orerInfo    = $ordersObj->dump(array('order_id'=>$order_id), 'order_id, order_bn, process_status, pay_status, ship_status');
        return $orerInfo;
    }
    
    /**
     * Wap发货单状态
     *
     * @param $outer_delivery_bn    ome发货单号
     * @return $orderInfo
     */
    public function formatDeliveryStatus($type='', $suffix='')
    {
        $data    = array();
        
        $data['status']          = array('处理中', '取消', '暂停', '已完成');
        $data['print_status']    = array('未打印', '已打印');
        $data['process_status']  = array('未打印', '已打印', '已校验', 4=>'已称重打包', 8=>'已物流交接');
        $data['confirm']         = array(1=>'已确认', 2=>'已拒绝', 3=>'未确认');
        $data['is_cod']         = array("true"=>'货到付款', "false"=>'款到发货');
        
        if($type)
        {
            return $suffix || $suffix === '0' ? $data[$type][$suffix] : $data[$type];
        }
        
        return $data;
    }
    
    /**
     * 通过门店自提仓库获取店铺详细信息
     *
     * @param $outer_delivery_bn    ome发货单号
     * @return $orderInfo
     */
    public function getBranchShopInfo($branch_id)
    {
        //$oBranchObj     = app::get('ome')->model('branch');

        $storeObj    = app::get('o2o')->model('store');

        $branch_info    = $storeObj->db->selectrow("SELECT branch_id, wms_id, branch_bn, name FROM sdb_ome_branch WHERE branch_id=" . $branch_id);
        
        $storeInfo    = array();
        if($branch_info)
        {
            $branch_info['branch_name']    = $branch_info['name'];
            unset($branch_info['name']);

            $storeInfo = $storeObj->dump(array('branch_id'=>$branch_info['branch_id']),'store_id, store_bn, name, area, shop_id, addr, contacter, mobile, tel');


            $storeInfo['store_name']    = $storeInfo['name'];
            $area    = explode(':', $storeInfo['area']);
            $storeInfo['store_addr']    = str_replace('/', '-', $area[1]) . $storeInfo['addr'];
            unset($storeInfo['name']);
        }
        
        return array_merge($branch_info, $storeInfo);
    }
    
    /**
     * 获取订单明细列表
     * 
     * @param int $order_id 订单id
     * @param bool $sort 是否要排序，默认不要。排序后的结果会按照普通商品、捆绑商品、赠品、配件等排列
     */
    function getOrderItemList($order_id, $sort=false)
    {
        $oOrder        = app::get('ome')->model('orders');
        $order_items   = array();
        
        if($sort)
        {
            $items    = $oOrder->dump($order_id, 'order_id', array("order_objects"=>array("*")));
            foreach($items['order_objects'] as $k=>$v)
            {
                $order_items[$v['obj_type']][$k] = $v;
                
                $sql    = "SELECT *,nums AS quantity FROM sdb_ome_order_items WHERE obj_id=".$v['obj_id']." AND item_type='product' ORDER BY item_type";
                foreach($oOrder->db->select($sql) as $it)
                {
                    $order_items[$v['obj_type']][$k]['order_items'][$it['item_id']] = $it;
                }
                
                $sql    = "SELECT *,nums AS quantity FROM sdb_ome_order_items WHERE obj_id=".$v['obj_id']." AND item_type<>'product' ORDER BY item_type";
                foreach($oOrder->db->select($sql) as $it)
                {
                    $order_items[$v['obj_type']][$k]['order_items'][$it['item_id']] = $it;
                }
            }
        }
        else 
        {
            $items    = $oOrder->dump($order_id, 'order_id', array("order_objects"=>array("*",array("order_items"=>array("*")))));
            foreach($items['order_objects'] as $oneobj)
            {
                foreach ($oneobj['order_items'] as $objitems)
                    $order_items[] = $objitems;
            }
        }
        
        return $order_items;
    }
    
    /**
     * 获取发货单明细
     */
    function getDeliveryItemList($delivery_bn)
    {
        $basicMaterialObj = app::get('material')->model('basic_material');
        $deliveryObj   = app::get('ome')->model('delivery');
        $dlyItemObj    = app::get('ome')->model('delivery_items');
        
        $deliveryInfo    = $deliveryObj->dump(array('delivery_bn'=>$delivery_bn), 'delivery_id');
        if(empty($deliveryInfo))
        {
            return '';
        }
        
        $delivery_id   = $deliveryInfo['delivery_id'];
        $items         = $dlyItemObj->getList('*', array('delivery_id' => $delivery_id), 0, -1);
        
        if ($items)
        {
            foreach ($items as $key => $item)
            {
                //将商品的显示名称改为后台的显示名称
                $productInfo= $basicMaterialObj->dump(array('material_bn'=>$items[$key]['bn']), 'material_name');
                
                $items[$key]['product_name'] = $productInfo['material_name'];
            }
        }
        
        return $items;
    }
    
    /**
     * 分页函数
     * @param unknown $rows
     * @param unknown $pagesize
     * @param string $url
     * @return string
     */
    function multi($rows, $pagesize, $url='')
    {
        $page    = intval($_GET['page']);
        
        $page_count		= ceil($rows/$pagesize);
        if($page_count <= 1){
            return '';
        }
        
        if($page <= 1 || $page == '') $page = 1;
        if($page >= $page_count) $page = $page_count;
        
        $pre_page		= ($page == 1)? 1 : $page - 1;
        $next_page		= ($page == $page_count)? $page_count : $page + 1 ;
        
        $pagenav	= '<div class="pager clearfix">';
        if($page == 1)
        {
            $pagenav	.= '<div class="page_pre"><a href="javascript:void(0);" class="nopre"><span>上一页</span></a></div>';
        }
        else
        {
            $pagenav	.= '<div class="page_pre"><a href="'.$url.'?page='.$pre_page.'"><span>上一页</span></a></div>';
        }
        
        $pagenav		.= '<div class="page_list">';
        $pagenav		.= '<div class="page_count"><span>'.$page.'/'.$page_count.'</span></div>';
        $pagenav		.= '<select onchange="window.location.href=this.value;" class="new_select">'."\n";
        
        for($i=1; $i<=$page_count; $i++)
        {
            if($i == $page)
            {
                $pagenav	.= '<option value="'.$url.'?page='.$i.'" selected>第'.$i.'页</option>'."\n";
            }
            else
            {
                $pagenav	.= '<option value="'.$url.'?page='.$i.'">第'.$i.'页</option>'."\n";
            }
        }
        $pagenav		.= "</select>";
        $pagenav		.= "</div>";
        
        if($page == $page_count)
        {
            $pagenav	.= '<div class="page_next"><a href="javascript:void(0);" class="nopre"><span>下一页</span></a></div>';
        }
        else
        {
            $pagenav	.= '<div class="page_next"><a href="'.$url.'?page='.$next_page.'"><span>下一页</span></a></div>';
        }
        $pagenav		.= "</div>";
        
        return $pagenav;
    }
}
